import React, { Component, memo } from 'react'
import { fetchArtList ,delArt} from 'api'
import { Card,Button,Table,Image, Tooltip,Tag,  Modal, message } from 'antd'
import {DownCircleOutlined   } from '@ant-design/icons'
import { cutString } from 'utils'
import moment from 'moment'
import XLSX from 'xlsx'


export default class ArtList extends Component {
  constructor(){
    super();
    this.state = {
      data: [], /* Array of Arrays e.g. [["a","b"],[1,2]] */
      delId: -1,
      current: 1,
      pageSize: 10,
      artList: [],
      total:0,
      visible: false, //弹出框状态
      columns : [
        {
          title: '标题',
          dataIndex: 'title',
          key: 'title',
        },
        {
          title: '作者',
          dataIndex: 'author',
          key: 'author',
        },
        {
          title: '描述',
          render: (row)=>{
            return (
              <Tooltip title={ row.desc }>
                <span> { cutString(row.desc) } </span>
              </Tooltip>
            )
          },
          key: 'desc',
        },
        {
          title: '封面图片',
          render: (row)=>{
            return (
              <Image width={50} src={row.thumb}></Image>
            )
          },
          key: 'thumb',
        },
        {
          title: '阅读次数',
          render: (row)=>{
            return (
              <Tag color={ row.readCount>500?'red':'green' }>
                { row.readCount }
              </Tag>
            )
          },
          key: 'readCount',
        },
        {
          title: '创建时间',
          render: (row)=>{
            return moment(row.createAt).format('YYYY/MM/DD')
          },
          key: 'createAt',
        },
        {
          title:"操作",
          render: (row,record,index)=>{
            return (
              <div>
                <Button 
                  type="primary"
                  onClick = { ()=>{
                    this.props.history.push(`/admin/artEdit/${row.id}`)
                  } } 
                  size="small">编辑</Button>
                <Button 
                  onClick = {
                    ()=>{
                      this.setState({ // 设置删除id 在确认拿到id
                        delId: row.id
                      })
                      this.showModal()
                    }
                  }
                size="small" danger>删除</Button>
              </div>
            )
          },
          key:"action"
        }
      ]
    }
  }
  render() {
    const { history } = this.props;
    return (
      <Card title={
        
       <div>
          <span>文章列表</span>
          <Button 
            style={{marginLeft:10}}
            onClick={
              ()=>{
                history.push('/admin/artAdd')
              }
            }
          >添加文章</Button>
       </div>
      } extra = {
        <Button 
          onClick={ 
            this.exportFile
           }
          icon={ <DownCircleOutlined/>}>
          导出excel
        </Button>
      }>


      {/* 弹出框 */}
      <Modal
          title="删除文章"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <p>您确认删除吗？</p>
          
        </Modal>
      {/* 弹出框 */}
        <Table 
          dataSource={this.state.artList} 
          columns={this.state.columns} 
          pagination={{
            current: this.state.current,
            pageSize:this.state.pageSize,
            total: this.state.total,
            onChange: (current,pageSize)=>{
              // 点击切换页面重新获取另一页数据
              console.log(current,pageSize)
              this.setState({
                current,
                pageSize
              },()=>{
                this.fetchArtList();
              })
            }
          }}
          />
      </Card>
    )
  }
  componentDidMount(){
    this.fetchArtList()
  }
  fetchArtList = ()=>{
    fetchArtList({
      current: this.state.current,
      pageSize:this.state.pageSize
    }).then(res=>{
      console.log(res)
      if(res.data.code === 200){
        this.setState({
          artList: res.data.data.lists,
          total: res.data.data.total
        },()=>{
          // 设置导出excel 内容
          this.setXlsx();
        })
      }
    })
  }
  showModal = () => { // 显示弹出框
    this.setState({
      visible: true,
    });
  };

  handleOk = e => { // 点击弹出框确认按钮
   
    delArt(this.state.delId).then(res=>{
      if(res.data.code === 200){
        
        message.success(res.data.msg,2,()=>{
          this.props.history.go(0)
        })
      }else{
        message.error(res.data.msg,2,()=>{
          this.props.history.go(0)
        })
      }
    })
    
    this.setState({
      visible: false,
    });
  };

  handleCancel = e => { // 点击弹出框取消按钮
    console.log(e);
    this.setState({
      visible: false,
    });
  }
  // 处理导出excel数据
  setXlsx = ()=>{
    // 处理导出excel 标题
     const titles = [
       "序号",
       "标题",
       "作者",
       "描述",
       "封面图片",
       "创建时间",
       "阅读次数",
       "详情内容"
     ]
     let data = [titles];
    //  处理每一行内容
    this.state.artList.forEach(art=>{
      console.log( Object.values(art) )
      data.push(Object.values(art))
    })
    this.setState({
      data
    })
  }
  // 表格数据导出为excel
  exportFile = ()=> {
		/* convert state to workbook */
		const ws = XLSX.utils.aoa_to_sheet(this.state.data);
		const wb = XLSX.utils.book_new();
		XLSX.utils.book_append_sheet(wb, ws, "SheetJS");
		/* generate XLSX file and send to client */
		XLSX.writeFile(wb, "文章列表.xlsx")
	}
}
